import React, { useContext, useState, useMemo } from 'react'
import Myback from './conponents/Myback'
import { Tabs, ProductCard, Tag, Button, Dialog } from 'react-vant'
import Ctx from '../store/Ctx'
import '../App.css'

export default function Sublist(props) {

  //获取数据
  let obj = useContext(Ctx)

  //定义一个状态
  let [tapIndex, setTapIndex] = useState(1)//1.推荐 2.小说 3.儿童

  //拿到所有列表 过滤出 符合条件的数据 实现切换
  let newlist = useMemo(() => {
    return obj.datalist.filter(item => {
      return item.typeId == tapIndex && item.sub
    })
  }, [obj.datalist, tapIndex])

  return (
    <div>
      {/* 导航栏 */}
      <Myback title={'订阅页面'} leftText={true}></Myback>

      {/* 标签页 */}
      <Tabs onChange={(index) => {
        setTapIndex(index + 1)

      }}>
        {['推荐', '小说', '儿童'].map(item => (
          <Tabs.TabPane key={item} title={item}></Tabs.TabPane>
        ))}
      </Tabs>

      {/* 商品数据渲染 渲染卡片 */}
      <div className='homelist'>
        {
          newlist.map(item => {``
            return <ProductCard
              onClick={() => {
                //跳转详情页并传参
                props.history.push({
                  pathname: '/details',
                  state: item.id
                })
              }}
              key={item.id}
              num={<Button size='small' round
                onClick={(e) => {
                  //阻止事件冒泡
                  e.stopPropagation()
                  //提示是否取消订阅
                  Dialog.confirm({
                    title: '提示',
                    message: '确定取消订阅吗',
                    onConfirm: () => { //确定
                      //切换订阅状态
                      obj.dispatch({
                        type: 'change_sub',
                        payload: item.id
                      })
                    },
                  }).catch(err => { }) //点击取消 捕获错误
                }}>
                取消订阅
              </Button>}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }
      </div>
    </div>
  )
}
